package meijuli.com.join51.business.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.bigkoo.pickerview.OptionsPickerView;
import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;
import meijuli.com.join51.business.R;
import meijuli.com.join51.business.activity.CertificationActivity;
import meijuli.com.join51.business.activity.PlatformDiscountActivity;
import meijuli.com.join51.business.aliyun.ImageUtils;
import com.jhx.common.http.ApiManager;
import com.jhx.common.http.HttpRequest;
import com.jhx.common.http.HttpResponse;
import com.jhx.common.http.ResponseCallback;
import meijuli.com.join51.business.location.LocationActivity;
import meijuli.com.join51.business.model.Area;
import meijuli.com.join51.business.model.BussinessCategory;
import meijuli.com.join51.business.model.City;
import com.jhx.common.model.EventBean;
import meijuli.com.join51.business.model.LocationDetails;
import meijuli.com.join51.business.model.Province;
import com.jhx.common.model.User;
import meijuli.com.join51.business.service.ApiService;
import meijuli.com.join51.business.utils.LogUtils;
import meijuli.com.join51.business.utils.SoftInputUtil;
import meijuli.com.join51.business.utils.StringUtil;
import com.jhx.common.utils.ToastUtil;
import com.jhx.common.utils.UserManager;
import retrofit2.Call;

/**
 * 添加店铺资料
 *
 * @author wenqin 2017-04-14 14:22
 */
public class AttestShopFragment extends PhotoFragment implements ImageUtils.SelectImageListener {
    EditText mDetailAddress;
    TextView mCategoryTxt;
    Button mNextBtn;
    ImageView mTakePhonePositive;
    Button mPreviousBtn;
    TextView addressText;
    TextView mAreaTxt;
    private String TAG = getClass().getName();
    private String mAddress;
    private String mArea;
    private double mLongitude;
    private double mLatitude;

    private OptionsPickerView<String> regionPickerView;
    private List<Province> regions;
    private String province, city, area;
    private long mProvinceId, mCityId, mAreaId;
    private String shopAddress;
    private User mUser;
    private long mCategoryId;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_attest_shop, container, false);
        mDetailAddress = view.findViewById(R.id.detail_address);
        mCategoryTxt = view.findViewById(R.id.edit_type);
        mNextBtn = view.findViewById(R.id.next_btn);
        mTakePhonePositive = view.findViewById(R.id.take_phone_positive);
        mPreviousBtn = view.findViewById(R.id.previous_btn);
        addressText = view.findViewById(R.id.text_address);
        mAreaTxt = view.findViewById(R.id.text_area);
        mNextBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                nextBtnClick();
            }
        });
        addressText.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                OnAddressClick();
            }
        });
        mCategoryTxt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                onCategoryClick();
            }
        });
        mPreviousBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                onPreviousBtnClick();
            }
        });
        mAreaTxt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                selectOpenAccAddress();
            }
        });
        mTakePhonePositive.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                onTakePhonePositiveClick();
            }
        });
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
        return view;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        ((CertificationActivity)getActivity()).setToolbarTitle("商铺信息");
        initView();
        initData();
    }

    private void initView() {

    }

    private void initData() {

        if (UserManager.get().checkUserNull(getActivity())) {
            return;
        }
        mUser = UserManager.get().getUser();

        if (!TextUtils.isEmpty(mUser.getShopAdd())
                && !TextUtils.isEmpty(mUser.getAddress())) {
            addressText.setText(mUser.getAddress());
            mDetailAddress.setText(mUser.getShopAdd());
            mAddress = mUser.getAddress();
            shopAddress = mUser.getShopAdd();
        }

        if (!TextUtils.isEmpty(mUser.getOneCategoryId())) {
            mCategoryTxt.setText(mUser.getCategoryName());
            mCategoryId = Long.valueOf(mUser.getOneCategoryId());
        }

        if (!TextUtils.isEmpty(mUser.getLocalShopPhoto())) {
            Glide.with(this).load(mUser.getLocalShopPhoto())
                    .error(R.mipmap.img_default)
                    .into(mTakePhonePositive);
            mPicPath1 = mUser.getShopPhoto();
            mLocalPicPath1 = mUser.getLocalShopPhoto();
        }

        if(!TextUtils.isEmpty(mUser.getArea())) {
            mArea = mUser.getArea();
            mAreaTxt.setText(mArea);
        }

        mAddress = mUser.getAddress();
        province = mUser.getProvinceName();
        city = mUser.getCityName();
        area = mUser.getTownName();
        mAreaId = mUser.getTownId();
        mProvinceId = mUser.getProvinceId();
        mCityId = mUser.getCityId();
    }

    void onPreviousBtnClick() {
        getActivity().onBackPressed();
    }

    void onTakePhonePositiveClick() {
        SoftInputUtil.get().hideSoftKeyboard(getActivity());
        toType = 1;
        showListDialog();
    }

    void onCategoryClick() {
        SoftInputUtil.get().hideSoftKeyboard(getActivity());

        showLoadingDialog();
        Call<HttpResponse<List<BussinessCategory>>> call = ApiManager.get().getApiService(ApiService.class)
                .getBusinessCategoryList();
        HttpRequest.getRequest().autoRecycle(AttestShopFragment.this).start(call, new ResponseCallback<List<BussinessCategory>>() {
            @Override
            public void onSuccess(String url, List<BussinessCategory> data) {
                dismissDialog();
                showCategoryDialog(data);
            }

            @Override
            public void onError(String url, int errorCode, String errorMsg) {
                super.onError(url, errorCode, errorMsg);
                dismissDialog();
            }
        });
    }

    void OnAddressClick() {
        SoftInputUtil.get().hideSoftKeyboard(getActivity());
        //启动定位
        Intent intent = new Intent(getActivity(), LocationActivity.class);
        startActivity(intent);
    }

    void nextBtnClick() {
        SoftInputUtil.get().hideSoftKeyboard(getActivity());

        if (TextUtils.isEmpty(mCategoryTxt.getText())) {
            ToastUtil.getInstance().showToast(getActivity(), "请选择行业类别");
            return;
        }

        if(TextUtils.isEmpty(mArea)) {
            ToastUtil.getInstance().showToast(getActivity(), "请选择区域(不可更改)");
            return;
        }

        if (TextUtils.isEmpty(mAddress)) {
            ToastUtil.getInstance().showToast(getActivity(), "请选择地址");
            return;
        }

        if (TextUtils.isEmpty(mLocalPicPath1)) {
            ToastUtil.getInstance().showToast(getActivity(), "照片不能为空");
            return;
        }

        if (TextUtils.isEmpty(mPicPath1) || mPicPath1.length() < 5) {
            ToastUtil.getInstance().showToast(getActivity(), "上传图片失败，请重试");
            return;
        }

        shopAddress = mDetailAddress.getText().toString();

        UserManager.get()
                .setCityId(mCityId)
                .setProvinceId(mProvinceId)
                .setTownId(mAreaId)
                .setProvinceName(province)
                .setCityName(city)
                .setTownName(area)
                .setArea(mArea)
                .setShopPhoto(mPicPath1)
                .setAddress(mAddress)
                .setShopAddress(shopAddress)
                .setOneCategoryId(mCategoryId + "")
                .setCategoryName(mCategoryTxt.getText().toString())
                .setLatitude(mLatitude)
                .setLongitude(mLongitude)
                .setLocalShopPhoto(mLocalPicPath1);

        Intent intent = new Intent(getActivity(), PlatformDiscountActivity.class);
        startActivity(intent);
    }

    private void showCategoryDialog(final List<BussinessCategory> data) {
        regionPickerView = new OptionsPickerView<>(this.getContext());
        ArrayList<String> options1 = new ArrayList<>();
        for (int i = 0; i < data.size(); i++) {
            options1.add(data.get(i).getName());
        }
        regionPickerView.setPicker(options1);
        regionPickerView.setCyclic(false);

        regionPickerView.setOnoptionsSelectListener(new OptionsPickerView.OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int option2, int options3) {
                mCategoryId = data.get(options1).getDmId();
                mCategoryTxt.setText(data.get(options1).getName());
            }
        });

        if (!regionPickerView.isShowing()) {
            regionPickerView.show();
        }
    }

    @Override
    protected void onUpLoadSuccess(String cloudKey, String sourceFilePath) {
        Glide.with(this).load(sourceFilePath).error(R.mipmap.img_default).into(mTakePhonePositive);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(EventBean eventBean) {
        switch (eventBean.getStatus()) {
            case EventBean.STATUS_UPDATE_LOCATION:
                LocationDetails locationDetails = (LocationDetails) eventBean.getEvent();
                if (locationDetails != null && !TextUtils.isEmpty(locationDetails.getCity())) {
                    LogUtils.i(TAG, "回传的结果为： " + locationDetails);
                    addressText.setText(locationDetails.getProvince() + locationDetails.getCity() + locationDetails.getDistrict());
                    mDetailAddress.setText(locationDetails.getStreet());
                    mLatitude = locationDetails.getLatitude();
                    mLongitude = locationDetails.getLongitude();
                    mAddress = addressText.getText().toString();
                    shopAddress = locationDetails.getStreet();
                }
                break;
            default:

                break;
        }
    }

    public void selectOpenAccAddress() {
        SoftInputUtil.get().hideSoftKeyboard(getActivity());
        if (null == regions || regions.size() <= 0) {
            getJsonProvince();
        } else {
            showProvinceList();
        }
    }

    /**
     * 显示省市选择对话框
     */
    private void showProvinceList() {
        regionPickerView = new OptionsPickerView<>(this.getContext());
        ArrayList<String> options1 = new ArrayList<>();
        ArrayList<ArrayList<String>> options2 = new ArrayList<>();
        ArrayList<ArrayList<ArrayList<String>>> options3 = new ArrayList<>();
        ArrayList<String> data2;
        ArrayList<String> data3;
        ArrayList<ArrayList<String>> tempList;
        if (null != regions && regions.size() > 0) {
            for (Province r : regions) {
                data2 = new ArrayList<>();
                tempList = new ArrayList<>();
                List<City> citys = r.getChildren();
                if (citys != null) {
                    for (City city : citys) {
                        data2.add(city.getText() + "");
                        data3 = new ArrayList<>();
                        List<Area> areas = city.getChildren();
                        if (areas != null) {
                            for (Area area : areas) {
                                data3.add(area.getText() + "");
                            }
                        }
                        tempList.add(data3);
                    }
                }
                options1.add(r.getText() + "");
                options2.add(data2);
                options3.add(tempList);
            }
        }

        regionPickerView.setPicker(options1, options2, options3, true);
        regionPickerView.setCyclic(false);
        // 区域选择结果
        regionPickerView.setOnoptionsSelectListener(new OptionsPickerView.OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int option2, int options3) {
                Province regionNew = regions.get(options1);
                province = regionNew.getText();
                city = regionNew.getChildren().get(option2).getText();
                area = regionNew.getChildren().get(option2).getChildren().get(options3).getText();
                mProvinceId = regionNew.getValue();
                mCityId = regionNew.getChildren().get(option2).getValue();
                mAreaId = regionNew.getChildren().get(option2).getChildren().get(options3).getValue();
                if(province.equals(city)) {
                    mArea = province + area;
                } else {
                    mArea = province + city + area;
                }
                mAreaTxt.setText(mArea);
            }
        });
        if (!regionPickerView.isShowing()) {
            regionPickerView.show();
        }
    }

    public void getJsonProvince() {
        regions = new Gson().fromJson(StringUtil.getJson(getActivity(),
                "CityData.json"), new TypeToken<List<Province>>() {
        }.getType());
        showProvinceList();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (regionPickerView != null && regionPickerView.isShowing()) {
            regionPickerView.dismiss();
        }
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        ((CertificationActivity)getActivity()).setToolbarTitle("商铺信息");
    }
}
